﻿using Aliyun.OSS;
using MassTransit.Util;
using ProductTool.Dao;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ProductTool.Service
{
    public class ImageService
    {
        ItemDao dao = new ItemDao();
        //下载图片到jd数据
        public void Process()
        {
            while (true)
            {
                try
                {
                    var data = dao.QueryNoImageForBook(100);
                    List<Task> taskList = new List<Task>();
                    foreach (var item in data.Rows)
                    {
                        taskList.Add(DownloadAsync(item["sku"].ToString(), item["image_path"].ToString()));
                        ;
                    }
                    Task.WaitAll(taskList.ToArray());
                    Console.WriteLine("current batch done-------------------");
                    if (data.Rows.Count == 0)
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Err:"+ex.Message);
                }
            }
        }

        async Task DownloadAsync(string sku, string image_path)
        {
            /*
          oss:

            http://oss-us-west-1.aliyuncs.com

             http://ec-us-west.oss-us-west-1.aliyuncs.com
             bucketName: ec-us-west
             AccessKeyID：LTAIetladkJrhOgV
             AccessKeySecret：LAKbjg9gdee2IHRTKZHtAtgKCEli2I        


          */

            var pic_path = "http://img30.360buyimg.com/vc/" + image_path;
            OssClient client = new OssClient("http://oss-us-west-1.aliyuncs.com", "LTAIetladkJrhOgV", "LAKbjg9gdee2IHRTKZHtAtgKCEli2I");
            var key = MD5Encrypt(image_path);
            try
            {
                HttpClient hClient = new HttpClient();
                var stream = await hClient.GetStreamAsync(pic_path);
                var result = client.PutObject("ec-us-west", "item/"+key, stream);
                if (!string.IsNullOrEmpty(result.RequestId) && result.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    dao.UpdateBookImage(key, sku);
                    Console.WriteLine($"update {sku} success");
                }
            }
            catch (Exception)
            {
                dao.UpdateBookImage("not found", sku);
            }
           
        }


        public string MD5Encrypt(string strText)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.Unicode.GetBytes(strText);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("x");
            }
            return byte2String;
        }



        public void ImportImage() {

            TaskFactory fac = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(10));
            List<Task> taskList = new List<Task>();
            while (true)
            {
                taskList.Clear();
                var list = dao.GetEmptyImgItem();
                if (list.Count==0)
                {
                    break;
                }
                foreach (var item in list)
                {
                    taskList.Add(fac.StartNew(()=> {
                        try
                        {
                            dao.CreateItemImage(item.sku, item.image_name);
                            dao.UpdateImageFlag(item.sku);
                            Console.WriteLine($"{item.sku} import success");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("err pass");
                        }
                    }));                   
                }
                Task.WaitAll(taskList.ToArray());
                Console.WriteLine("batch------------------------------------------------------");
            }
        }
    }
}
